<?php

namespace app\admin\model\tongcheng;

use addons\tongcheng\library\MapService;
use addons\tongcheng\model\BaseModel;
use traits\model\SoftDelete;

class ZoneModel extends BaseModel
{

    use SoftDelete;


    // 表名
    protected $name = 'tongcheng_zone';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'is_default_text'
    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);

            ZoneConfigModel::create([
                'zone_id' => $row[$pk],
            ]);
        });

        self::afterWrite(function ($row) {
            // 如果是默认区域，将其他区域设置为非默认
            if ($row['is_default'] == 1) {
                self::where('is_default', 1)->update(['is_default' => 0]);
                self::where('id', $row['id'])->update(['is_default' => 1]);
            }
        });
    }


    public function getStatusList()
    {
        return ['1' => __('Status 1'), '0' => __('Status 0')];
    }

    public function getIsDefaultList()
    {
        return ['1' => __('Is_default 1'), '0' => __('Is_default 0')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list  = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsDefaultTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_default']) ? $data['is_default'] : '');
        $list  = $this->getIsDefaultList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function config()
    {
        return $this->hasOne(ZoneConfigModel::class, 'zone_id', 'id');
        // return $this->hasOne(ZoneConfigModel::class, 'zone_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 获取区域配置
     * @param $zone_id
     * @return ZoneConfigModel|null
     */
    public static function getZoneConfig($zone_id, $regain = true)
    {
        $config = ZoneConfigModel::get([
            'zone_id' => $zone_id,
        ]);

        if (!$config) {
            $config = ZoneConfigModel::create([
                'zone_id' => $zone_id,
            ]);
            if ($regain) {
                $config = ZoneConfigModel::get([
                    'zone_id' => $zone_id,
                ]);
            }
        }

        return $config;
    }

    /**
     * 根据经纬度获取最近的区域
     * @param $lng
     * @param $lat
     * @return array
     */
    public static function getNearZone($lng, $lat, $address = null)
    {
        $position = "{$lng},{$lat}";
        $zones    = self::where('status', 1)->select();
        // $default_zone = null;

        foreach ($zones as &$zone) {
            // if (!$default_zone && $zone['is_default'] == 1) {
            //     $default_zone = $zone;
            // }

            // 匹配到区一致
            if ($address && !empty($address['address_component']['street']) && $address['address_component']['street'] == $zone['street']) {
                return $zone;
            }

            $zone['distance'] = 0;
            if (!empty($zone['lng']) && !empty($zone['lat'])) {
                // 计算直线距离
                $zone['distance'] = MapService::getDistanceByLine($position, "{$zone['lng']},{$zone['lat']}");
            }
        }

        // 按距离排序
        usort($zones, function ($a, $b) {
            return $a['distance'] - $b['distance'];
        });

        // return $default_zone ? $default_zone : $zones[0];
        return $zones[0];
    }
}
